﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

using Rio.Framework.Localisation;

using Telerik.Windows.Controls;

namespace Rio.Manager.Application.Behaviors
{
    public class ExportExcelGridViewBehavior : Behavior<Button>
    {
        #region Fields

        public static readonly DependencyProperty GridViewToExportProperty = 
            DependencyProperty.Register("GridViewToExport", typeof(RadGridView), typeof(ExportExcelGridViewBehavior), null);

        #endregion Fields

        #region Constructors

        public ExportExcelGridViewBehavior()
            : base()
        {
        }

        #endregion Constructors

        #region Properties

        public RadGridView GridViewToExport
        {
            get { return (RadGridView)GetValue(GridViewToExportProperty); }
            set { SetValue(GridViewToExportProperty, value); }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Called when [attached].
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.Click += AssociatedObject_Click;
        }

        /// <summary>
        /// Called when [detaching].
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.Click -= AssociatedObject_Click;
        }

        /// <summary>
        /// Handles the Click event of the AssociatedObject control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void AssociatedObject_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "xls";
            saveFileDialog.Filter = "Excel Files | *.xls";

            if (saveFileDialog.ShowDialog() == true)
            {
                using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.OpenFile()))
                {
                    streamWriter.Write(GridViewToExport.ToExcelML(true, true));

                    MessageBox.Show(Resx.GetLabel(ResxRioManager.REPORT_CLOSE_MSG), String.Empty, MessageBoxButton.OK);
                }
            }
        }

        #endregion Methods
    }
}